package com.allwees.bs.c.module.order.chain.create.handler;

import com.allwees.bs.c.module.ops.service.PromoUseService;
import com.allwees.bs.c.module.ops.service.UserCouponService;
import com.allwees.bs.c.module.order.chain.create.request.OrderCreateRequest;
import com.allwees.bs.c.module.order.context.bo.CouponComputeBo;
import com.allwees.bs.c.module.order.context.bo.CouponComputeItemBo;
import com.allwees.bs.c.module.order.context.bo.UserCouponBo;
import com.allwees.bs.c.module.order.context.compute.ComputeStrategy;
import com.allwees.core.common.context.AbstractHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.stream.Collectors;

@Component
public class CalculateDiscountHandler extends AbstractHandler<OrderCreateRequest> {

    @Autowired
    private UserCouponService userCouponService;
    @Autowired
    private PromoUseService promoUseService;
    @Autowired
    private ComputeStrategy computeStrategy;

    @Override
    public OrderCreateRequest handler(OrderCreateRequest request) {
        UserCouponBo userCoupon = findUseCoupon(request.getUserCouponUuid(), request.getUserPromoLogUuid());
        if (null != userCoupon) {
            request.setDiscountRate(userCoupon.getFaceValue());
        }

        CouponComputeBo computeBo = new CouponComputeBo(request)
                .setItems(request.getItems().stream().map(CouponComputeItemBo::new).collect(Collectors.toList()));

        computeStrategy.compute(userCoupon, computeBo).rest(request);

        return doNext(request);
    }


    private UserCouponBo findUseCoupon(String userCouponUuid, String userPromoLogUuid) {
        if (StringUtils.isBlank(userCouponUuid) && StringUtils.isBlank(userPromoLogUuid)) {
            return null;
        }

        UserCouponBo userCouponBo = null;
        if (StringUtils.isNotBlank(userCouponUuid)) {
            userCouponBo = new UserCouponBo(userCouponService.load(userCouponUuid));
        } else if (StringUtils.isNotBlank(userPromoLogUuid)) {
            userCouponBo = new UserCouponBo(promoUseService.findByLogUuid(userPromoLogUuid));
        }
        return userCouponBo;
    }
}
